package com.jm.web.form.baseitem;

import java.io.IOException;
import java.sql.ResultSet;

import javax.servlet.jsp.JspWriter;

import net.sf.json.JSONObject;


import com.jm.utils.AttributeBuilder;
import com.jm.utils.StringBuilderEx;
import com.jm.utils.StringHelper;
import com.jm.utils.Utils;
import com.jm.web.form.support.FieldItem;
import com.jm.web.form.support.FormItem;
import com.jm.web.tags.support.BaseTag;

public class ComboxItem extends ListItem{
	protected boolean bNoButton = false;//是否需要下攔選項
	protected boolean bSingle = false;
	protected StringBuffer data = new StringBuffer();
	protected boolean bDataEmpty = true;
	protected String otherdata = "";
	
	public ComboxItem() {};
	
	@Override
	public void InitTag(BaseTag tag) {
		super.InitTag(tag);
		this.setNodeName(FieldItem.TAG_ITEMNAME);
	}
	
	@Override
	protected void processDataSourcelist() {
		if(this.getUtils() != null && StringHelper.Length(this.strDataSource) > 0 && StringHelper.Length(this.strSql) > 0){
			try {
				StringBuilderEx temp = null;
				String key = StringHelper.Format("combox-%1$s-%2$s",this.strDataSource,this.strSql);
				if(this.getBaseTag().getPage().listItemDataContainsKey(key)){
					otherdata = (String)this.getBaseTag().getPage().getListItemData(key);
				}else{
					temp = new StringBuilderEx();
					ResultSet rs = this.getUtils().executeQuery(this.strDataSource, this.strSql);
					int colCount = 0;
					if(rs != null)
						colCount = rs.getMetaData().getColumnCount();
					
					while(rs.next())
					{
						JSONObject json = new JSONObject();
						if(colCount == 1){
							String colName1 = StringHelper.getValue(rs.getMetaData().getColumnName(1));
							String colValue1 = StringHelper.getValue(rs.getString(1)) ;
//							Item item = new Item(colValue1,
//									(colName1.startsWith("i18n")) ? this.getUtils().i18n(colValue1) : colValue1);
							
							json.put("value",colValue1);
							json.put("text",colName1.startsWith("i18n") ? this.getUtils().i18n(colValue1) : colValue1);
							
						}else if(colCount >= 2){
							String colName2 = StringHelper.getValue(rs.getMetaData().getColumnName(2));
							String colValue2 = StringHelper.getValue(rs.getString(2)) ;
//							Item item = new Item(rs.getString(1),
//									(colName2.startsWith("i18n")) ? this.getUtils().i18n(colValue2) : colValue2);
							
							json.put("value",StringHelper.getValue(rs.getString(1)));
							json.put("text",(colName2.startsWith("i18n")) ? this.getUtils().i18n(colValue2) : colValue2);
							
							if(colCount > 2){
								for(int i = 3 ;i<=colCount ;i++){
									String colNamei = StringHelper.getValue(rs.getMetaData().getColumnName(i));
									String colValuei = StringHelper.getValue(rs.getString(i)) ;
//									item.SetExtValue(rs.getMetaData().getColumnName(i),
//											(colNamei.startsWith("i18n")) ? this.getUtils().i18n(colValuei) : colValuei);
									json.put(StringHelper.getValue(rs.getMetaData().getColumnName(i)),
											(colNamei.startsWith("i18n")) ? this.getUtils().i18n(colValuei) : colValuei);
								}
							}
						}
						
						String realValue = json.getString("value");
						String text = json.getString("text");
						
						if(this.IsContainsKey("textconfig")){
							//處理text值
							String strConfigValue = Utils.getConfigFormatString("{"+this.GetExtValue("textconfig","")+"}",json);
							if(!StringHelper.IsNullOrEmpty(strConfigValue)){
								text = strConfigValue; 
							}
						}
						
						if(this.IsContainsKey("valueconfig")){
							//處理實際值
							String strConfigValue = Utils.getConfigFormatString("{"+this.GetExtValue("valueconfig","")+"}",json);
							if(!StringHelper.IsNullOrEmpty(strConfigValue)){
								realValue = strConfigValue; 
							}
						}
						
						json.remove("value");
						json.remove("text");
						
						json.put("value",text);
						json.put("realvalue",realValue);
						
						if(!bDataEmpty){
							temp.Append(",");
						}else{
							bDataEmpty = false;
						}
						temp.Append(json.toString());
					}
					rs.close();
					data.append(temp.toString());
					this.getBaseTag().getPage().addListItemData(key,this.getName());
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Override
	protected void processRawcodelist() {
		if(StringHelper.IsNullOrEmpty(this.strCodeList))
			return ;
		
		String [] sets = this.strCodeList.split("[;]");
		for(int i = 0 ;i<sets.length;i++)
		{
			String strTemp = sets[i].trim();
			if(StringHelper.IsNullOrEmpty(strTemp))
				continue;
			
			String [] keyvalue  = strTemp.split("[|]");
			String realValue = keyvalue[0];
			String text = keyvalue[0];
			
			if(keyvalue.length == 2){
				if(StringHelper.IsNullOrEmpty(keyvalue[0]))
					continue;
				
				if(StringHelper.IsNullOrEmpty(keyvalue[1]))
					continue;
				realValue = keyvalue[0];
				text = keyvalue[1];
				
				//addListItem(new Item(keyvalue[0], keyvalue[1]));
			}else if(keyvalue.length == 1){
				if(StringHelper.IsNullOrEmpty(keyvalue[0]))
					continue;
				
				//addListItem(new Item(keyvalue[0], keyvalue[0]));
				realValue = keyvalue[0];
				text = keyvalue[0];
			}
			
			JSONObject json = new JSONObject();
			json.put("text",text);
			json.put("value",realValue);
			
			if(this.IsContainsKey("textconfig")){
				//處理text值
				String strConfigValue = Utils.getConfigFormatString("{"+this.GetExtValue("textconfig","")+"}",json);
				if(!StringHelper.IsNullOrEmpty(strConfigValue)){
					text = strConfigValue; 
				}
			}
			
			if(this.IsContainsKey("valueconfig")){
				//處理實際值
				String strConfigValue = Utils.getConfigFormatString("{"+this.GetExtValue("valueconfig","")+"}",json);
				if(!StringHelper.IsNullOrEmpty(strConfigValue)){
					realValue = strConfigValue; 
				}
			}
			
			json.remove("value");
			json.remove("text");
			
			json.put("value",text);
			json.put("realvalue",realValue);
			if(!this.bDataEmpty){
				data.append(",");
			}else{
				this.bDataEmpty = false;
			}
			data.append("{");
			data.append("\"value\":\"").append(text).append("\"");
			data.append(",\"realvalue\":\"").append(realValue).append("\"");
			data.append("}");
		}
	}
	
	@Override
	public void renderBegin(JspWriter writer) {
		if(this.getBaseTag() != null && this.getBaseTag().isDSP())
			super.renderBegin(writer);
	}
	
	@Override
	public void renderEnd(JspWriter writer) {
		if(this.getBaseTag() != null && this.getBaseTag().isDSP())
			super.renderEnd(writer);
	}
	
	@Override
	public void onRenderSingleBody(JspWriter writer, FormItem item) {
		StringBuilderEx sb = new StringBuilderEx();
		int textWidth = Integer.parseInt(StringHelper.getValue(this.getWidth(),"100").replace("px",""));
		sb.Append("<div id=\"%2$s_field\" style=\"width:%1$spx;left: 0;position: relative;top: 0;height:22px;_height:20px;\">",textWidth,this.getName());
		
		
		if(!this.isNoButton())
			textWidth = textWidth - 17 ;
		this.setWidth(StringHelper.Format("%1$spx",textWidth));
		this.setStyle(StringHelper.Format("%1$s;width:%2$spx;",this.getStyle(),textWidth));
		
		if(!this.isSingle()){
			//1.combox text框 
			sb.Append("\r\n<input type='text' xtype=\"combobox_text\" ");
			sb.Append(" onblur=\"$P.form.comboboxblur(this)\" ");
			AttributeBuilder attributesBuilder = new AttributeBuilder();
			attributesBuilder.InitFromHashtable(this.extAttrList,true);
			if(!StringHelper.IsNullOrEmpty(this.GetExtValue("textvalue","")))
			{
				sb.Append("value='%1$s'",this.GetExtValue("textvalue",""));
			}
			FillAttributeBuilder(attributesBuilder);
			
			attributesBuilder.Set("name",StringHelper.Format("%1$s_text",this.getName()));
			attributesBuilder.Set("id",StringHelper.Format("%1$s_text",this.getId()));
			attributesBuilder.Set("hiddenid",StringHelper.Format("%1$s",this.getId()));
			attributesBuilder.Append("style","float:left;_height:16px !important;border: 1px solid #7F9DB9 ;");
			attributesBuilder.Append("class",", ax-input-text");
			attributesBuilder.Remove("required");
			attributesBuilder.Remove("rule");
			attributesBuilder.Remove("msg");
			sb.Append(attributesBuilder.ToOutputString());
			sb.Append(" />");
			
			//2.combox 隱藏框
			sb.Append("\r\n<input type='hidden' xtype=\"combobox\" ");
			sb.Append(" id='%1$s'",this.getId());
			sb.Append(" caption='%1$s'",this.getCaption());
			sb.Append(" name='%1$s'",this.getName());
			if(!StringHelper.IsNullOrEmpty(this.getValue()))
			{
				sb.Append(" value='%1$s'",this.getValue());
			}
			if(!StringHelper.IsNullOrEmpty(this.GetExtValue("action","")))
			{
				sb.Append(" action='%1$s'",this.GetExtValue("action",""));
			}
			
			if(!StringHelper.IsNullOrEmpty(this.GetExtValue("actionvalue","")))
			{
				sb.Append(" actionvalue='%1$s'",this.GetExtValue("actionvalue",""));
			}
			sb.Append(" />");
		}else{
			//1.combox 
			sb.Append("\r\n<input type='text' xtype=\"combobox\" ");
			sb.Append(" onblur=\"$P.form.comboboxblur(this)\" ");
			AttributeBuilder attributesBuilder = new AttributeBuilder();
			attributesBuilder.InitFromHashtable(this.extAttrList,true);
			FillAttributeBuilder(attributesBuilder);
			attributesBuilder.Append("style","float:left;_height:16px;border: 1px solid #7F9DB9 ;");
			attributesBuilder.Set("single","true");
			attributesBuilder.Remove("required");
			attributesBuilder.Remove("rule");
			attributesBuilder.Remove("msg");
			
			
			if(!StringHelper.IsNullOrEmpty(this.getValue()))
			{
				attributesBuilder.Set(TAG_VALUE.toLowerCase(), this.getValue());
			}
			
			sb.Append(attributesBuilder.ToOutputString());
			sb.Append(" />");
		}
		
		if(!this.isNoButton()){
			sb.Append("<img class=\"ax-form-arrow-trigger\"  style=\"margin:0;padding:0;height: 19px; width: 17px;cursor: pointer;position: absolute;_bottom:0;%1$s\"",this.GetExtValue("imgStyle", ""));
			sb.Append(" src=\""+this.getBaseTag().getPage().getContextPath()+"/include/images/default/s.gif\"");
			sb.Append(" id=\"%1$s_dropdown\" />",this.getId());
		}
		sb.Append("</div>");
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void OnSetProperty(String strName, String strValue) {
		if("nobutton".equalsIgnoreCase(strName))
		{
			this.bNoButton = StringHelper.GetValue(strValue,this.bNoButton);
			return;
		}
		
		if("single".equalsIgnoreCase(strName)){
			this.bSingle = StringHelper.GetValue(strValue,this.bSingle);
			return;
		}
		
		super.OnSetProperty(strName, strValue);
	}
	
	/**
	 * @return
	 * 是
	 */
	public boolean isNoButton(){
		return this.bNoButton;
	}
	
	/**
	 * @return
	 * 是否是單行模式
	 */
	public boolean isSingle(){
		return this.bSingle;
	}

	public StringBuffer getData() {
		return data;
	}


	public void setData(StringBuffer data) {
		this.data = data;
	}


	public String getOtherdata() {
		return otherdata;
	}


	public void setOtherdata(String otherdata) {
		this.otherdata = otherdata;
	}
}
